import { toRefs } from '@vue/composition-api'
import usePagination from '@/hooks/usePagination'

export default {
  data () {
    return {
      tableLoading: false,
    }
  },

  props: {
    tableArgs: {
      type: Object,
      default: () => ({}),
    },
  },

  setup () {
    // 分页
    const {
      pagination,
      handlePageChange,
      handleSizeChange,
      handlePrevClick,
      handleNextClick,
      updatePaginationParams,
    } = usePagination()
    const { sizes, data, layout } = toRefs(pagination)

    return {
      layout,
      pagination: data,
      pageSizes: sizes,
      handlePageChange,
      handleSizeChange,
      handlePrevClick,
      handleNextClick,
      updatePaginationParams,
    }
  },

  computed: {
    tableProps () {
      return {
        columns: this.columns,
        loading: this.tableLoading,
        size: 'middle',
        pagination: this.paginationProps,
        dataSource: this.pagination.items,
        scroll: { x: '1200px' },
      }
    },

    paginationProps () {
      const { total, page, per_page } = this.pagination
      const _self = this

      return {
        total,
        showSizeChanger: true,
        current: page,
        pageSize: per_page,
        // hideOnSinglePage: true,
        pageSizeOptions: _self.pageSizes,
        // pageSize 变化的回调
        onShowSizeChange (current, per_page) {
          console.log(per_page, _self.pageSizes, '1-11')
           _self.updatePaginationParams({
            per_page,
            page: 1,
          })
          _self.tableHooksRequest()
        },
        // 页码改变的回调，参数是改变后的页码及每页条数
        onChange (page, pageSize) {
          _self.updatePaginationParams({
            page,
          })
          _self.tableHooksRequest()
        },
      }
    },
  },

  methods: {
    refreshTableData () {
      return new Promise((resolve, reject) => {
        this.updatePaginationParams({
          page: 1,
        })
        this.tableHooksRequest()
          .then(data => {
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    getTableDatas (request, args) {
      return new Promise((resolve, reject) => {
        this.tableLoading = true
        this.handlePageChange(request, args)
          .then((data) => {
            resolve(data)
          })
          .catch((error) => {
            reject(error)
          })
          .finally(() => {
            this.tableLoading = false
          })
      })
    },
  },
}
